package com.hs.jhzd.utils;

import java.io.IOException;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonMessageConverter extends Jackson2JsonMessageConverter {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.amqp.support.converter.Jackson2JsonMessageConverter#
	 * fromMessage(org.springframework.amqp.core.Message)
	 */
	@Override
	public String fromMessage(Message message) throws MessageConversionException {
		String content = "";
		MessageProperties properties = message.getMessageProperties();
		if (properties != null) {
			String contentType = properties.getContentType();
			if (contentType != null && contentType.contains("json")) {
				String encoding = properties.getContentEncoding();
				if (encoding == null) {
					encoding = getDefaultCharset();
				}
				try {
					content = new String(message.getBody(), encoding);
				} catch (IOException ex) {
					log.error("Failed to convert Message content", ex);
					throw new MessageConversionException("Failed to convert Message content", ex);
				}
			} else {
				log.warn("Could not convert incoming message with content-type [" + contentType + "]");
			}
		}
		return content;
	}

}
